package com.xinghou.platform.util.map;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javapns.org.json.JSONObject;

public class BaiduMapUtils {
	
	/**
	 * 根据经纬度得到城市名
	 * @param x	经度
	 * @param y 纬度
	 * @param type 1.返回省名，2返回城市名
	 * @return
	 * @throws IOException
	 */
	public static String getCityByXY(String y,String x,int type) throws IOException {
		String key = "qQKBSSFmbzAO1Icn08hlfu2e"; // 秘钥
		String url = String.format("http://api.map.baidu.com/geocoder/v2/?ak=%s&location=%s,%s&output=json&pois=0",key,y, x);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		InputStreamReader insr = null;
		BufferedReader br = null;
		try {
			httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
			if (httpsConn != null) {
				insr = new InputStreamReader(httpsConn.getInputStream(),
						"UTF-8");
				br = new BufferedReader(insr);
				String data = br.readLine();
				System.out.println(data);
				JSONObject json = new JSONObject(data);
				if(!json.getString("status").equals("0"))
				{
					return null;
				}
				String info = json.getString("result");
				JSONObject json2 = new JSONObject(info);
				JSONObject temp = new JSONObject(json2.getString("addressComponent"));
				if(type==2){
					String city = temp.getString("city");
					return city;
				}else{
					String province = temp.getString("province");
					return province;
				}
			}
		} catch (Exception e) {
			return null;
			//e.printStackTrace();
		} finally {
			if (insr != null) {
				insr.close();
			}
			if (br != null) {
				br.close();
			}
		}
		return null;
	}
}
